package org.xgj.zhangben;

import java.util.HashSet;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.xgj.zhangben.util.Constant;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class AuthorityInterceptor extends AbstractInterceptor {

	/**
	 * 不包含的用户登录路径
	 */
	private static final Set<String> EXINCLUDE_USER_LOGIN_PATH = new HashSet<String>();
	static {
		EXINCLUDE_USER_LOGIN_PATH.add("user/base!register.action");
		EXINCLUDE_USER_LOGIN_PATH.add("user/base!login.action");
	}
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		if (validateUserLogin(invocation)) {
			return invocation.invoke();
		} else {
			ServletActionContext.getRequest().setAttribute("jumpPageType",
					"selfPage");
			ServletActionContext.getRequest().setAttribute("msg",
					"<script>alert('" + "没有登录,请登录！" + "');</script>");
			ServletActionContext.getRequest().setAttribute("jump", "index.jsp");
			return "jump";
		}

	}

	/**
	 * 验证用户登录
	 * 
	 * @param invocation
	 */
	private Boolean validateUserLogin(ActionInvocation invocation) {
		HttpServletRequest request = ServletActionContext.getRequest();
		LoginedUser loginedUser = (LoginedUser) request.getSession()
				.getAttribute(Constant.LOGINED_USER);
		for (String url : EXINCLUDE_USER_LOGIN_PATH) {
			if (request.getRequestURI().toLowerCase().endsWith(
					url.toLowerCase())) {
				return true;
			}
		}
		if (loginedUser != null) {
			return true;
		}
		return false;
	}

}
